<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Popular extends CI_Controller {
	public function index()
	{
                $data['title'] = "Tonight's Meal Votes";
                $data['data'] = array ();
                
                $this->load->model('mealtimes');
                
                $mealtime = $this->mealtimes->getMealID(date("Y"),date("m"),date("j"));
                $servetime = strtotime($mealtime->mealtime_servetime);

                if (time() >= $servetime){
                    $servetime_text = "closed as of ".unix_to_time($servetime);
                }
                else{
                    $servetime_text = "open until ".unix_to_time($servetime);
                }
                
                $meal_votes = $this->getVotes();
                
                $data['js'] = array("graph.js");
                $data['css'] = array("graph.css");
                
                $data['data'] = array(
                    "date_today" => date("l jS \of F Y"),
                    "meal_votes" => $meal_votes,
                    "servetime" => $servetime_text
                    );
                
                $data['view'] = "current_orders/view_popular";
                $this->load->view('view_template',$data);
	}
        
        private function getVotes(){
            $this->load->model("mealtimes");
            $this->load->model("user_votes");
            $tonightsMeals = $this->mealtimes->getMealsYMD(date("Y"),date("m"),date("j"));

            $meal_votes = array();

            foreach($tonightsMeals->result() as $result){
                $numVotes = $this->user_votes->getNumVotes($result->mealtime_id, $result->meal_id);
                $meal_votes[$result->meal_title] = $numVotes;
            }
            
            return $meal_votes;
        }
        
        public function refresh(){
            echo json_encode($this->getVotes());
        }
}